<template>
  <div class="pdf-viewer-container" :class="{ 'fullscreen-mode': isFullscreen }">
    <!-- 遮罩层 -->
    <div v-if="showModal" class="pdf-modal" @click.self="closeModal">
      <div class="pdf-modal-content">
        <!-- 关闭按钮 -->
        <button class="close-btn" @click="closeModal">×</button>

        <!-- 控制栏 -->
        <div v-if="!isFullscreen" class="pdf-controls">
          <button :disabled="pageNum <= 1" @click="prevPage">上一页</button>
          <span class="page-info">{{ pageNum }} / {{ totalPages }}</span>
          <button :disabled="pageNum >= totalPages" @click="nextPage">下一页</button>
          <button @click="toggleFullscreen">
            {{ isFullscreen ? '退出全屏' : '全屏' }}
          </button>
          <button @click="downloadPdf">下载</button>
        </div>

        <!-- PDF 查看区域 -->
        <div class="pdf-container">
          <div ref="pdfContainer" class="pdf-canvas">
            <div v-if="!pdfUrl" class="loading">加载 PDF 中...</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>

import * as pdfjsLib from 'pdfjs-dist'

export default {
  name: 'PdfViewer',
  props: {
    pdfUrl: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      showModal: false,
      pdf: null,
      pageNum: 1,
      totalPages: 0,
      isFullscreen: false,
      targetWidth: 302.4,
      targetHeight: 378
    }
  },
  mounted() {
    pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.16.105/pdf.worker.min.js'
    document.addEventListener('fullscreenchange', this.handleFullscreenChange)
    document.addEventListener('keydown', this.handleKeyDown)
  },
  beforeDestroy() {
    document.removeEventListener('fullscreenchange', this.handleFullscreenChange)
    document.removeEventListener('keydown', this.handleKeyDown)
    if (this.isFullscreen) {
      this.exitFullscreen()
    } // 确保组件销毁时退出全屏
  },
  methods: {
    openModal() {
      this.showModal = true
      this.$nextTick(() => {
        this.loadPdf()
      })
    },
    closeModal() {
      if (this.isFullscreen) {
        this.exitFullscreen()
      } // 关闭时退出全屏
      this.showModal = false
      this.resetPdfState()
    },
    resetPdfState() {
      this.pdf = null
      this.pageNum = 1
      this.totalPages = 0
      const container = this.$refs.pdfContainer
      if (container) container.innerHTML = ''
    },
    async loadPdf() {
      if (!this.pdfUrl || !this.showModal) return

      try {
        this.resetPdfState()
        const container = this.$refs.pdfContainer

        this.pdf = await pdfjsLib.getDocument(this.pdfUrl).promise
        this.totalPages = this.pdf.numPages
        await this.renderPage(this.pageNum)
      } catch (error) {
        console.error('Error loading PDF: ', error)
        this.closeModal()
      }
    },
    async renderPage(pageNum) {
      if (!this.pdf) return

      const page = await this.pdf.getPage(pageNum)
      const container = this.$refs.pdfContainer
      container.innerHTML = ''

      // 根据全屏状态调整尺寸
      const containerWidth = container.clientWidth - 40
      const containerHeight = this.isFullscreen
        ? window.innerHeight - 100
        : container.clientHeight - 40

      const viewport = page.getViewport({ scale: 1.0 })
      const scale = Math.min(
        (containerWidth / viewport.width) * devicePixelRatio,
        (containerHeight / viewport.height) * devicePixelRatio,
        4.0
      )

      const canvas = document.createElement('canvas')
      const context = canvas.getContext('2d')
      const scaledViewport = page.getViewport({ scale })

      canvas.width = scaledViewport.width
      canvas.height = scaledViewport.height
      canvas.style.maxWidth = '100%'
      canvas.style.height = 'auto'

      await page.render({
        canvasContext: context,
        viewport: scaledViewport
      }).promise

      container.appendChild(canvas)
    },
    nextPage() {
      if (this.pageNum < this.totalPages) {
        this.pageNum++
        this.renderPage(this.pageNum)
      }
    },
    prevPage() {
      if (this.pageNum > 1) {
        this.pageNum--
        this.renderPage(this.pageNum)
      }
    },
    toggleFullscreen() {
      if (this.isFullscreen) {
        this.exitFullscreen()
      } else {
        this.enterFullscreen()
      }
    },
    enterFullscreen() {
      const element = this.$el
      if (element.requestFullscreen) {
        element.requestFullscreen()
      } else if (element.webkitRequestFullscreen) {
        element.webkitRequestFullscreen()
      } else if (element.msRequestFullscreen) {
        element.msRequestFullscreen()
      }
    },
    exitFullscreen() {
      if (document.exitFullscreen) {
        document.exitFullscreen()
      } else if (document.webkitExitFullscreen) {
        document.webkitExitFullscreen()
      } else if (document.msExitFullscreen) {
        document.msExitFullscreen()
      }
    },
    handleFullscreenChange() {
      this.isFullscreen = !!document.fullscreenElement
      if (this.isFullscreen) {
        this.$nextTick(() => {
          this.renderPage(this.pageNum) // 全屏后重新渲染适应新尺寸
        })
      }
    },
    handleKeyDown(e) {
      if (!this.showModal) return
      if (e.key === 'Escape' && this.isFullscreen) {
        this.exitFullscreen()
      } else if (e.key === 'ArrowRight') {
        this.nextPage()
      } else if (e.key === 'ArrowLeft') {
        this.prevPage()
      } else if (e.key === 'f' || e.key === 'F') {
        this.toggleFullscreen()
      }
    },
    downloadPdf() {
      const link = document.createElement('a')
      link.href = this.pdfUrl
      link.download = 'document.pdf'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    }
  }
}
</script>

<style scoped>
.pdf-viewer-container {
  position: relative;
}

.pdf-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.7);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

/* 全屏模式下的样式 */
.fullscreen-mode .pdf-modal {
  background-color: #fff;
}

.fullscreen-mode .pdf-modal-content {
  width: 100% !important;
  height: 100% !important;
  max-width: 100% !important;
  border-radius: 0 !important;
  padding: 10px !important;
}

.pdf-modal-content {
  position: relative;
  width: 80%;
  height: 90%;
  max-width: 900px;
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
  display: flex;
  flex-direction: column;
}

.pdf-container {
  flex: 1;
  position: relative;
  overflow: auto;
  margin-top: 10px;
}

.pdf-canvas {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 300px;
}

.pdf-controls {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 15px;
  padding: 10px;
  background: #f5f5f5;
  border-radius: 4px;
  margin-bottom: 10px;
  flex-wrap: wrap;
}

.pdf-controls button {
  padding: 5px 10px;
  min-width: 80px;
  background: #fff;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
}

.pdf-controls button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.page-info {
  font-weight: bold;
  min-width: 80px;
  text-align: center;
}

.close-btn {
  position: absolute;
  top: 10px;
  right: 10px;
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #666;
  z-index: 1001;
}

.close-btn:hover {
  color: #333;
}

.loading {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  font-size: 18px;
  color: #666;
}

/* 全屏模式下的控制栏样式 */
.fullscreen-mode .pdf-controls {
  background: rgba(245, 245, 245, 0.9);
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1002;
  margin-bottom: 0;
  padding: 5px 10px;
}

.fullscreen-mode .close-btn {
  position: fixed;
  top: 15px;
  right: 15px;
  z-index: 1003;
  color: #333;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 50%;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
}

@media (max-width: 768px) {
  .pdf-modal-content {
    width: 95%;
    height: 95%;
    padding: 15px;
  }

  .pdf-controls {
    gap: 8px;
  }

  .pdf-controls button {
    min-width: 60px;
    padding: 3px 6px;
    font-size: 14px;
  }
}
</style>
